﻿using sMES_Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using sMES_Base.service;
using System.Data;
using unload_scrap_acc_from_machine_process.Models;

namespace unload_scrap_acc_from_machine_process
{
    /// <summary>
	/// 元件[unload_scrap_acc_from_machine_process]
    /// <auth>JingHuang</auth><time>2019/1/2 上午 09:05:36</time>
    /// <description></description>
    /// <list>
    ///     <modify>
    ///         <auth></auth><mantis>0053953</mantis><time></time>
    ///         <description>設備卸下異常模具</description>
    ///     </modify>
    ///     <modify>
    ///         <auth>Rex</auth><mantis>0055889</mantis><time></time>
    ///         <description>模具异常下模后找不到历程资料</description>
    ///     </modify>
    /// </list>
    /// </summary>
    public class unload_scrap_acc_from_machine_process_utility : BaseUtility
    {
        public unload_scrap_acc_from_machine_process_utility(ref BaseService CurrentService) : base(ref CurrentService)
        {
        }


        public RES_unload_scrap_acc_from_machine_process unload_acc_from_machine_process(REQ_unload_scrap_acc_from_machine_process content)
        {
            RES_unload_scrap_acc_from_machine_process OutData = new RES_unload_scrap_acc_from_machine_process();
            StringBuilder sbSQL = new StringBuilder();
            DataTable dtWIPContAccessory = new DataTable();


            foreach (CDO_scrap_details _CDO_scrap_details in content.scrap_details)
            {

                DataTable dtLotNo = new DataTable();
                bool GoPass = false;
                // enforce = 0 第一次執行,需要檢查設備上是否有生產批(Running)
                if (content.enforce.Equals(0))
                {
                    sbSQL.Clear();
                    sbSQL.Append(" SELECT LOTNO");
                    sbSQL.Append(" FROM TBLWIPTEMP_EQUIPMENT");
                    sbSQL.Append(" WHERE EQUIPMENTNO = '" + _CDO_scrap_details.machine_no  + "'");
                    dtLotNo = CurrentService.GetDao().Query(sbSQL.ToString());

                    if (dtLotNo == null || dtLotNo.Rows.Count == 0) GoPass = true;
                }
                else GoPass = true;

                if (GoPass)
                {
                    //確認是否目前模具有在使用中
                    sbSQL.Clear();
                    sbSQL.Append("select * from tblWIPCont_Accessory where AccessoryNo='" + _CDO_scrap_details.accessory_no + "'");

                    dtWIPContAccessory = CurrentService.GetDao().Query(sbSQL.ToString());

                    //20210610 modify by summerteng for M#93641 模治具异常下模报错
                    //沒有進站即做異常下模動作，則會出現此錯誤訊息，實務情境上是有可能上模後，
                    //在未生產前發現模具有損壞、故障等異常情況而下模，在此做此卡控不符合實務情境，故調整邏輯，將原卡控邏輯移除

                    // '還未有 治具使用歷程記錄，tblWIPCont_Accessory
                    //if (dtWIPContAccessory.Equals(null))
                    //    throw new ServiceException(ServiceCode.ParamsValidateException, package_err("ACCESSORYNO") + ":" + _CDO_scrap_details.accessory_no + package_err("TBLWIPCONT_ACCESSORY") + package_err("DATA NOT FOUND"));

                    //if (dtWIPContAccessory.Rows.Count.Equals(0))
                    //    throw new ServiceException(ServiceCode.ParamsValidateException, package_err("ACCESSORYNO") + ":" + _CDO_scrap_details.accessory_no + package_err("TBLWIPCONT_ACCESSORY") + package_err("DATA NOT FOUND"));

                    sbSQL.Clear();
                    sbSQL.Append("update tblWIPCont_Accessory set NEXTDAY= To_Date('" + Convert.ToDateTime(content.next_date).ToString("yyyy/MM/dd") + "','YYYY/MM/DD HH24:MI:SS'), reasonno='" + content.reason_no + "' ");
                    sbSQL.Append(", STATE='1'");
                    sbSQL.Append(", ENDTIME = SYSDATE ");
                    sbSQL.Append(" where AccessoryNo='" + _CDO_scrap_details.accessory_no + "' and ENDTIME is Null and STATE is null");
                    CurrentService.GetDao().ExecuteNonQuery(sbSQL.ToString());
                    sbSQL.Clear();

                    // 20240126 add by duzm M#0156362: 【好利来】正式区，模治具寿命扣除量与出站量不一致
                    // 处理未下模前出站后不在今日生产任务中的记录
                    sbSQL.Append("UPDATE TBLWIPCONT_ACCESSORY SET ENDTIME = SYSDATE WHERE accessoryno = '" + _CDO_scrap_details.accessory_no + "' AND EQUIPMENTNO = '" + _CDO_scrap_details.machine_no + "'  AND ENDTIME IS NULL");
                    CurrentService.GetDao().ExecuteNonQuery(sbSQL.ToString());
                    sbSQL.Clear();

                    // 0055889: 模具异常下模后找不到历程资料 改至 saveAccStateLog 執行
                    //// '模具狀態改為"0" 入庫
                    //sbSQL.Clear();
                    //sbSQL.Append("update TBLEMSACCESSORYSTATE　set ACCESSORYSTATE='0' where AccessoryNo='" + _CDO_scrap_details.accessory_no + "'");
                    //CurrentService.GetDao().ExecuteNonQuery(sbSQL.ToString());
                    //M#65970 异常下模 直接送修
                    //該模具編號 寫 log
                    string now_time = DateTime.Now.ToString("yyyy/MM/dd H:mm:ss");
                    saveAccStateLog(_CDO_scrap_details.accessory_no, content.reason_no, "0", now_time);
                    if (content.call_repair_reason_no != null && content.call_repair_reason_no != "")
                    {
                        saveAccStateLog(_CDO_scrap_details.accessory_no, content.call_repair_reason_no, "3", now_time);
                    }
                    //判斷是否為組合模具
                    sbSQL.Append("SELECT * FROM tblEMSCombineACCState  a JOIN tblEMSAccessoryState b");
                    sbSQL.Append(" ON A.AccessoryNo = B.AccessoryNo WHERE CombineACCNo = '"+ _CDO_scrap_details.accessory_no + "'");
                    DataTable com_acc_data = this.CurrentService.GetDao().Query(sbSQL.ToString());
                    if(com_acc_data.Rows.Count > 0)
                    {
                        //組合要跑底下多筆
                        foreach (DataRow item in com_acc_data.Rows)
                        {
                            string accessory_no = item["AccessoryNo"].ToString();
                            if(accessory_no != _CDO_scrap_details.accessory_no)
                            {
                                saveAccStateLog(accessory_no, content.reason_no, "0", now_time);
                                if (content.call_repair_reason_no != null && content.call_repair_reason_no != "")
                                {
                                    saveAccStateLog(accessory_no, content.call_repair_reason_no, "3", now_time);
                                }
                            }
                        }
                    }
                    //刪除tblEMSEQPACCState(上下模畫面不顯示此筆資料)
                    sbSQL.Clear();
                    sbSQL.Append("Delete From tblEMSEQPACCState Where AccessoryNo = '" + _CDO_scrap_details.accessory_no + "'");
                    CurrentService.GetDao().ExecuteNonQuery(sbSQL.ToString());
                    OutData.exec_result = 1;

                    // 修改模治具下模数量
                    sbSQL.Clear();
                    sbSQL.Append($@" select count(1) from TBLCUSMoldMoves where AccessoryNo = '{_CDO_scrap_details.accessory_no}' and AccessoryVersion = '{_CDO_scrap_details.accessory_version}' ");
                    if (CurrentService.GetDao().Query1RecordInt(sbSQL.ToString()) > 0)
                    {
                        sbSQL.Clear();
                        sbSQL.Append($@" UPDATE TBLCUSMoldMoves
                                     SET HistoricalMoldDowns = HistoricalMoldDowns + 1,CurrentMoldDowns = CurrentMoldDowns + 1
                                     WHERE AccessoryNo = '{_CDO_scrap_details.accessory_no}' and AccessoryVersion = '{_CDO_scrap_details.accessory_version}' ");
                        CurrentService.GetDao().ExecuteNonQuery(sbSQL.ToString());
                    }
                    else
                    {
                        sbSQL.Clear();
                        sbSQL.Append($@" INSERT TBLCUSMoldMoves ( Creator,CreateDate,AccessoryNo,AccessoryVersion,
                                                              HistoryCount,CurrentMoldUps,HistoricalMoldDowns,CurrentMoldDowns,
                                                              repairStatus,FutureUse,modifiedDate) 
                                     VALUES ('{CurrentService.GetServiceInfo().account}',Getdate(),'{_CDO_scrap_details.accessory_no}','{_CDO_scrap_details.accessory_version}',
                                             0,0,1,1,
                                             null,0,null) ");
                        CurrentService.GetDao().ExecuteNonQuery(sbSQL.ToString());
                    }
                }
                else
                {
                    OutData.exec_result = 0;
                    string strLotNo = "";
                    foreach (DataRow drLotNo in dtLotNo.Rows)
                    {
                        if (strLotNo == "") strLotNo = Convert.ToString(drLotNo[0]);
                        else strLotNo = strLotNo + "、<br>" + Convert.ToString(drLotNo[0]);
                    }
                    OutData.message = package_err("EQUIPMENTNO") + ":" + _CDO_scrap_details.machine_no  + " " +
                        package_err("THERERUNING") + "(" + strLotNo + ")," + package_err("SUGGEST1_1") + "," +
                        package_err("SUGGEST1_2") + "," + package_err("continue ask") + "?";
                    /* 設備編號：xxxx 仍有生產中的生產批(XXX、xxx)，建議先執行出站報工後再做模治具更換作業，否則生產批出站的模治具壽命耗用將會被算在新的模治具上，是否繼續? */

                }                
            }            
            return OutData;
        }

        public void saveAccStateReason()
        {

        }

        /// <summary>
        /// 紀錄異常下模 modi from 下模.change_ACC_state
        /// </summary>
        /// <param name="accessory_no"></param>
        /// <param name="reasonno"></param>               原因編號         M#65970 add by a991241234
        /// <param name="state"></param>                  狀態             M#65970 add by a991241234
        /// <param name="default_time"></param>           預設時間         M#65970 add by a991241234
        public void saveAccStateLog (string accessory_no, string reason_no,string state,string default_time)
        {
            StringBuilder sbSQL = new StringBuilder();

            // 0055889: 模具异常下模后找不到历程资料
            // 將紀錄寫入 TBLEMSACCESSORYSTATELOG 
            // 下模時填入方式相同，將上一個狀態的資訊填入Log中
            // 填入TBLEMSACCESSORYSTATELOG時，將所選的異常原因填入Description欄位中

            DataTable dtEmsaccstate = new DataTable();

            sbSQL.Clear();
            sbSQL.Append(" Select a.ACCSerialNo,a.AccessoryState,a.StartTime,a.UserNo,a.Description,a.AccessoryNo,a.AccessoryVersion,a.APPLYTIME,a.ACCUMULATEQTY,b.* ");
            sbSQL.Append(" From tblEMSAccessoryState a, TBLEQPACCESSORYBASIS b ");
            sbSQL.Append(" Where a.AccessoryNo = '" + accessory_no + "' ");
            sbSQL.Append(" And a.AccessoryVersion = (select AccessoryVersion from TBLEQPACCESSORYBASIS ");
            sbSQL.Append(" where AccessoryNo = '" + accessory_no + "' and CURVERSION = 1) ");
            sbSQL.Append(" and a.AccessoryNo = b.AccessoryNo and a.AccessoryVersion = b.AccessoryVersion");

            //檢查是否有資料
            dtEmsaccstate = CurrentService.GetDao().Query(sbSQL.ToString());

            if (dtEmsaccstate.Rows.Count.Equals(0))
                throw new ServiceException(ServiceCode.ParamsValidateException, package_err("tblEMSAccessoryState") + package_err("DATA NOT FOUND"));
                        
            sbSQL.Clear();
            sbSQL.Append("INSERT INTO TBLEMSACCESSORYSTATELOG(ACCSerialNo, AccessoryNo, AccessoryVersion, AccessoryState, AccessoryType");
            sbSQL.Append(", UserNo, StartTime, EndTime, Description");
            sbSQL.Append(", APPLYTIME, ACCUMULATEQTY ) ");
            sbSQL.Append("Values('" + dtEmsaccstate.Rows[0]["ACCSerialNo"] + "','" + dtEmsaccstate.Rows[0]["AccessoryNo"] + "'");
            sbSQL.Append(",'" + dtEmsaccstate.Rows[0]["AccessoryVersion"] + "','" + dtEmsaccstate.Rows[0]["AccessoryState"] + "'");
            sbSQL.Append(",'" + dtEmsaccstate.Rows[0]["AccessoryType"] + "','" + dtEmsaccstate.Rows[0]["UserNo"] + "'");
            sbSQL.Append(", To_Date('" + ((DateTime)(dtEmsaccstate.Rows[0]["StartTime"])).ToString("yyyy/MM/dd H:mm:ss") + "', 'YYYY/MM/DD HH24:MI:SS')");
            sbSQL.Append(",'"+default_time+ "'");
            //sbSQL.Append(",'" + reasonno + "' ");
            sbSQL.Append(",'' ");
            if (!dtEmsaccstate.Rows[0]["APPLYTIME"].Equals(DBNull.Value))
                sbSQL.Append(", To_Date('" + ((DateTime)(dtEmsaccstate.Rows[0]["APPLYTIME"])).ToString("yyyy/MM/dd H:mm:ss") + "', 'YYYY/MM/DD HH24:MI:SS'),");
            else
                sbSQL.Append(",'"+default_time+ "',");

            if (!dtEmsaccstate.Rows[0]["ACCUMULATEQTY"].Equals(DBNull.Value))
                sbSQL.Append(dtEmsaccstate.Rows[0]["ACCUMULATEQTY"] + ")");
            else
                sbSQL.Append("0)");
            CurrentService.GetDao().ExecuteNonQuery(sbSQL.ToString());

            // '模具狀態改為 state ("0" 入庫, "3" 維修)
            // '變更State,現況變更要重新產生一新的SerialNo
            sbSQL.Clear();
            sbSQL.Append(" Update tblEMSAccessoryState Set AccessoryState = "+state);
            sbSQL.Append(" ,StartTime = '"+default_time+ "'");
            sbSQL.Append(" ,ACCSerialNo ='" + InitACCSerialNo() + "'");
            sbSQL.Append(" ,UserNo = '" + BaseService._ServiceInfo.account + "'");
            //sbSQL.Append(" ,Description = '" + reasonno + "'");
            sbSQL.Append(" Where AccessoryNo = '" + dtEmsaccstate.Rows[0]["AccessoryNo"] + "' And AccessoryVersion = '" + dtEmsaccstate.Rows[0]["AccessoryVersion"] + "'");
            CurrentService.GetDao().ExecuteNonQuery(sbSQL.ToString());
            //M#65970 异常下模 直接送修
            //write log tblEMSEQPACCState to tblEMSEQPACCStateLog for M#65970 add by a991241234
            sbSQL.Clear();
            sbSQL.Append("SELECT * FROM tblEMSEQPACCState WHERE AccessoryNo = '" + accessory_no + "'");
            DataTable tblEMSEQPACCState_data = this.CurrentService.GetDao().Query(sbSQL.ToString());
            if (tblEMSEQPACCState_data.Rows.Count > 0)
            {
                sbSQL.Clear();
                string tblEMSEQPACCState_cloum_sql = "'" + dtEmsaccstate.Rows[0]["ACCSerialNo"] + "',";
                tblEMSEQPACCState_cloum_sql += "'" + tblEMSEQPACCState_data.Rows[0]["EQUIPMENTTYPE"] + "',";
                tblEMSEQPACCState_cloum_sql += "'" + tblEMSEQPACCState_data.Rows[0]["EQUIPMENTNO"] + "',";
                tblEMSEQPACCState_cloum_sql += "'" + tblEMSEQPACCState_data.Rows[0]["ACCESSORYTYPE"] + "',";
                tblEMSEQPACCState_cloum_sql += "'" + tblEMSEQPACCState_data.Rows[0]["ACCESSORYNO"] + "',";
                tblEMSEQPACCState_cloum_sql += "'" + tblEMSEQPACCState_data.Rows[0]["ACCESSORYVERSION"] + "',";
                tblEMSEQPACCState_cloum_sql += "'" + tblEMSEQPACCState_data.Rows[0]["USERNO"] + "',";
                tblEMSEQPACCState_cloum_sql += "'" + Convert.ToDateTime(tblEMSEQPACCState_data.Rows[0]["STARTTIME"]).ToString("yyyy/MM/dd H:mm:ss") + "',";
                tblEMSEQPACCState_cloum_sql += "'"+ default_time + "'";
                sbSQL.Append("INSERT INTO TBLEMSEQPACCSTATELOG");
                sbSQL.Append("   (ACCSERIALNO,EQUIPMENTTYPE,EQUIPMENTNO,ACCESSORYTYPE,ACCESSORYNO,ACCESSORYVERSION,USERNO,STARTTIME,ENDTIME)    ");
                sbSQL.Append("VALUES");
                sbSQL.Append("  (" + tblEMSEQPACCState_cloum_sql + ")  ");
                CurrentService.GetDao().ExecuteNonQuery(sbSQL.ToString());
                if (string.IsNullOrEmpty(reason_no) == false)
                {
                    //write tblEMSAccessoryStateReason for M#65970 add by a991241234
                    sbSQL.Clear();
                    sbSQL.Append("Select * From tblACCReasonBasis Where ISSUESTATE = 2  AND ReasonNo = '" + reason_no + "'");
                    DataTable tblACCReasonBasis_data = this.CurrentService.GetDao().Query(sbSQL.ToString());
                    if (tblACCReasonBasis_data.Rows.Count.Equals(0))
                        throw new ServiceException(ServiceCode.ParamsValidateException, package_err("CALL_REPAIR_REASON_NOT_FIND"));
                    string tblEMSAccessoryStateReason_cloum_sql = "";
                    tblEMSAccessoryStateReason_cloum_sql += "'" + dtEmsaccstate.Rows[0]["ACCSerialNo"] + "',";
                    tblEMSAccessoryStateReason_cloum_sql += "'" + dtEmsaccstate.Rows[0]["AccessoryNo"] + "',";
                    tblEMSAccessoryStateReason_cloum_sql += "'" + dtEmsaccstate.Rows[0]["AccessoryVersion"] + "',";
                    tblEMSAccessoryStateReason_cloum_sql += "'" + dtEmsaccstate.Rows[0]["AccessoryState"] + "',";
                    tblEMSAccessoryStateReason_cloum_sql += "'" + state + "',";
                    tblEMSAccessoryStateReason_cloum_sql += "'" + tblACCReasonBasis_data.Rows[0]["ReasonType"] + "',";
                    tblEMSAccessoryStateReason_cloum_sql += "'" + tblACCReasonBasis_data.Rows[0]["ReasonNo"] + "',";
                    tblEMSAccessoryStateReason_cloum_sql += "'" + tblACCReasonBasis_data.Rows[0]["ReasonName"] + "'";
                    sbSQL.Clear();
                    sbSQL.Append("INSERT INTO tblEMSAccessoryStateReason");
                    sbSQL.Append("(ACCSerialNo,AccessoryNo,AccessoryVersion,ORGACCState,NewACCState,ReasonType,ReasonNo,ReasonName)");
                    sbSQL.Append("VALUES");
                    sbSQL.Append("(" + tblEMSAccessoryStateReason_cloum_sql + ")");
                    CurrentService.GetDao().ExecuteNonQuery(sbSQL.ToString());
                }
            }
        }
        /// <summary>
        /// 將產生ACC Serial
        /// </summary>
        /// <returns></returns>
        private string InitACCSerialNo()
        {
            string ACCSerialNo = "", strYear, strMonth;
            var strTempDate = new object();
            var SerialNo_ACCSTATELOG = new object();
            var SerialNo_ACCSTATEDATE = new object();
            StringBuilder sbSQL = new StringBuilder();
            int intSerial = 1;
            strYear = DateTime.Now.Year.ToString().Substring(2, 2); //2018 取18
            strMonth = DateTime.Now.Month.ToString("d2");

            if ("oracle".Equals(CurrentService.GetDao().DBType.ToLower()))
            {
                //'1.檢查Sequenct物件是否存在
                string sequenceName = "ACCSTATELOG" + strYear + strMonth;
                sbSQL.Clear();
                sbSQL.Append("Select Object_Name from User_Objects Where Object_Type = 'SEQUENCE' And Object_Name = '" + sequenceName + "'");
                DataTable dtTmp = CurrentService.GetDao().Query(sbSQL.ToString());

                if (dtTmp == null || dtTmp.Rows.Count == 0)
                {
                    // 20220517 modify by chenshibo for#112397: 模治具异常下模报错
                    sbSQL.Clear();
                    sbSQL.Append("Create Sequence " + sequenceName + " Increment by 1 " + " Start with 1 " + " MaxValue 99999999 MinValue 0 Cycle Cache 20");

                    //'呼叫執行SQL指令
                    CurrentService.GetDao().ExecuteImmediately(sbSQL.ToString());
                }
                dtTmp.Clear();

                //'2.取得Sequence的流水號
                sbSQL.Clear();
                sbSQL.Append("Select " + sequenceName + ".NextVal as NextValue From Dual");
                dtTmp = CurrentService.GetDao().Query(sbSQL.ToString());

                if (dtTmp != null && dtTmp.Rows.Count > 0) intSerial = Convert.ToInt32(dtTmp.Rows[0]["NextValue"]);
                else throw new ServiceException(ServiceCode.DataAbnormalException, package_err("Get NextVal of sequence object:") + sequenceName + package_err("fail") + " !");
                
            }
            else
            {
                sbSQL.Clear();
                sbSQL.Append("Select SerialNo From tblSysSerialNo Where FunctionName = 'ACCSTATEDATE'");
                SerialNo_ACCSTATEDATE = CurrentService.GetDao().Query1RecordColumn(sbSQL.ToString());

                //防呆
                if (SerialNo_ACCSTATEDATE == null)
                {
                    //'填入新的日期,格式化存入(ex:0412,因Serial為數值故無法存入0412,故一律前面加上1)
                    sbSQL.Clear();
                    sbSQL.Append("Insert Into tblSysSerialNo (FunctionName, SerialNo) Values ('ACCSTATEDATE',1" + strYear + strMonth + ")");
                    //20210525 Modify by Tim for#XXX：[效能]立即異動表格，預防表鎖.
                    CurrentService.GetDao().ExecuteImmediately(sbSQL.ToString());

                    // '月的序號
                    sbSQL.Clear();
                    sbSQL.Append("Select SerialNo From tblSysSerialNo Where FunctionName = 'ACCSTATELOG'");
                    SerialNo_ACCSTATELOG = CurrentService.GetDao().Query1RecordColumn(sbSQL.ToString());

                    if (SerialNo_ACCSTATELOG == null)
                    {
                        sbSQL.Clear();
                        sbSQL.Append("Insert Into tblSysSerialNo (FunctionName, SerialNo) Values ('ACCSTATELOG', 1)");
                        //20210525 Modify by Tim for#XXX：[效能]立即異動表格，預防表鎖.
                        CurrentService.GetDao().ExecuteImmediately(sbSQL.ToString());
                    }
                    else
                    {
                        sbSQL.Clear();
                        sbSQL.Append("Update tblSysSerialNo Set SerialNo = 1 Where FunctionName = 'ACCSTATELOG'");
                        //20210525 Modify by Tim for#XXX：[效能]立即異動表格，預防表鎖.
                        CurrentService.GetDao().ExecuteImmediately(sbSQL.ToString());
                    }

                    intSerial = 1;
                }
                else
                {
                    strTempDate = SerialNo_ACCSTATEDATE;

                    //'更新日期,格式化存入(ex:041208,因Serial為數值故無法存入041208,故一律前面加上1)
                    sbSQL.Clear();
                    sbSQL.Append("Update tblSysSerialNo Set SerialNo = 1" + strYear + strMonth + " Where FunctionName = 'ACCSTATEDATE'");
                    //20210525 Modify by Tim for#XXX：[效能]立即異動表格，預防表鎖.
                    CurrentService.GetDao().ExecuteImmediately(sbSQL.ToString());

                    // '比較日期

                    if ((strTempDate.ToString()).Equals("1" + strYear + strMonth)) //'同月
                    {
                        // '取出月的序號
                        sbSQL.Clear();
                        sbSQL.Append("Select SerialNo From tblSysSerialNo Where FunctionName = 'ACCSTATELOG'");
                        SerialNo_ACCSTATELOG = CurrentService.GetDao().Query1RecordColumn(sbSQL.ToString());
                        if (SerialNo_ACCSTATELOG == null)
                        {
                            sbSQL.Clear();
                            sbSQL.Append("Insert Into tblSysSerialNo (FunctionName, SerialNo) Values ('ACCSTATELOG', 1)");
                            //20210525 Modify by Tim for#XXX：[效能]立即異動表格，預防表鎖.
                            CurrentService.GetDao().ExecuteImmediately(sbSQL.ToString());

                            intSerial = 1;
                        }
                        else
                        {
                            // '填入新SerialNo
                            sbSQL.Clear();
                            sbSQL.Append("Update tblSysSerialNo Set SerialNo = " + (Convert.ToInt32(SerialNo_ACCSTATELOG) + 1) + " Where FunctionName = 'ACCSTATELOG'");
                            //20210525 Modify by Tim for#XXX：[效能]立即異動表格，預防表鎖.
                            CurrentService.GetDao().ExecuteImmediately(sbSQL.ToString());

                            intSerial = (Convert.ToInt32(SerialNo_ACCSTATELOG) + 1);
                        }
                    }
                    else
                    {
                        //'月的序號
                        sbSQL.Clear();
                        sbSQL.Append("Select SerialNo From tblSysSerialNo Where FunctionName = 'ACCSTATELOG'");
                        SerialNo_ACCSTATELOG = CurrentService.GetDao().Query1RecordColumn(sbSQL.ToString());

                        if (SerialNo_ACCSTATELOG == null)
                        {
                            sbSQL.Clear();
                            sbSQL.Append("Insert Into tblSysSerialNo (FunctionName, SerialNo) Values ('ACCSTATELOG', 1)");
                            //20210525 Modify by Tim for#XXX：[效能]立即異動表格，預防表鎖.
                            CurrentService.GetDao().ExecuteImmediately(sbSQL.ToString());
                        }
                        else
                        {
                            sbSQL.Clear();
                            sbSQL.Append("Update tblSysSerialNo Set SerialNo = 1 Where FunctionName = 'ACCSTATELOG'");
                            //20210525 Modify by Tim for#XXX：[效能]立即異動表格，預防表鎖.
                            CurrentService.GetDao().ExecuteImmediately(sbSQL.ToString());
                        }
                        intSerial = 1;
                    }
                }
            }
            // 'ACC Serial No編碼規則
            // '一碼前置字元 +　西元年後兩碼　＋ 兩碼月份 + 七碼流水號
            // '每月流水號歸零，例如S06010000001

            ACCSerialNo = "A" + strYear + strMonth + intSerial.ToString("0000000");
            return ACCSerialNo;
        }

        /// <summary>
        /// 封裝語系
        /// 模組名稱 + errvalue
        /// </summary>
        /// <param name="errvalue"></param>
        /// <returns></returns>
        private string package_err(string errvalue)
        {
            //return CurrentService.GetResource("[%" + CurrentService.GetServiceInfo().service_module + "." + errvalue + "%]");
            return CurrentService.GetResource("[%Module_ACC." + errvalue + "%]");
        }

    }

}
